from .PageElement import PageElement
from .Selector import Selector
from selenium.webdriver.remote.webdriver import WebDriver
from .WaitElement import WaitElement
from ...exception.errorcode import ErrorCode
from ...exception.TestException import TestException


class Switch2Frame(PageElement):
    def __init__(self, driver: WebDriver, selector_str, selector_str_inner,selector_type=Selector.CLASS_NAME,selector_type_inner=Selector.CLASS_NAME):
        super().__init__(driver, selector_str, selector_type)
        self.frame = None
        self.wait_element = WaitElement(driver,selector_str_inner,selector_type_inner)

    def switch_to_frame(self):
        """
        进入到iframe里面去
        :return:
        """
        self.frame = self._get_web_elements()[0]
        if self.frame is not None:
            self._driver.switch_to.frame(self.frame)
        else:
            raise TestException.by_error_code(ErrorCode.FRAME_NOT_EXIST)

    def wait_element_ready(self):
        self.switch_to_frame()
        self.wait_element.wait_element_ready()
        self.out_frame()

    def out_frame(self):
        """
        退出iframe
        :return:
        """
        self._driver.switch_to_default_content()
